<?php

namespace App\Http\Controllers\V1\BasicData;

use App\Models\V1\ApplyDorms;
use App\Models\V1\NewStudent;
use App\Models\V1\Clothes;
use App\Models\V1\ClotheSize;
use App\Models\V1\ResultClothes;
use App\Models\V1\NewArrival;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

class UniformCollectController extends Controller
{
    /**
     * 显示校服信息汇总管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $codes = $this->getEnrollmentCodes();
        $data['codes'] = $codes;
        $arrival_code = $this->getArrivalCodes();
        $data['arrival_code'] = $arrival_code;
        return view('v1.collect.uniform', $data);
    }

    /**
     * 获取校服信息汇总数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];
        // 获取符合查询条件的校服数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = !empty($request->get('keywords')) ? $request->get('keywords') : '%%';
        $arrival_code = !empty($request->get('arrival_code')) ? $request->get('arrival_code') : $this->getArrivalCodes();
        
        // 获取符合查询条件的校服数据
        $data = $this->getUniformsCollectList($currentPage, $rows, $keywords, $arrival_code);
        
        if (!empty($data)) {
            $formatList = array();
            $count = count($data) > 0 ? count($data) : 0;
            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $formatItem['ClotheCode'] = $item->ClotheCode;
                    $formatItem['ClotheName'] = $item->ClotheName;
                    $formatItem['ClotheSizeCode'] = $item->ClotheSizeCode;
                    $formatItem['ClotheSizeName'] = $item->ClotheSizeName;
                    // 根据衣服code获取该件衣服相关信息
                    $ClotheData = Clothes::where('code', $item->ClotheCode)->where('arrival_code', $arrival_code)->first();
                    $formatItem['remark'] = $ClotheData->remark;
                    $formatItem['count'] = $ClotheData->count;
                    $formatItem['unit'] = $ClotheData->unit;
                    $formatItem['sex_limit'] = $ClotheData->sex_limit == 1 ? '男女不限' : ($ClotheData->sex_limit == 2 ? '男生领用' : '女生领用');
                    
                    // 计算该衣服下的男生和女生人数
                    $boy_count = 0;
                    $girl_count = 0;
                    $StudentData = NewStudent::where('arrival_code', 'like' , '%'.$arrival_code.'%')->get();
                    // 获取当前学期下的学生exam_code集合
                    $StudentExamCode = array();
                    if(!empty($StudentData)){
                        for($i=0;$i<count($StudentData);$i++){
                            $StudentExamCode[] = $StudentData[$i]->exam_code;
                        }
                    }
                    $ResultClothes = ResultClothes::whereIn('exam_code', $StudentExamCode)->where('cloth_code', $item->ClotheCode)->where('size_code', $item->ClotheSizeCode)->get();
                    if(!empty($ResultClothes)){
                        for($i=0;$i<count($ResultClothes);$i++){
                            $exam_code = $ResultClothes[$i]->exam_code;
                            $StudentInfo = NewStudent::where('exam_code', $exam_code)->first();
                            if(!empty($StudentInfo)){
                                if($StudentInfo->sex == 1){
                                    $boy_count++;
                                }elseif($StudentInfo->sex == 2){
                                    $girl_count++;
                                }
                            }
                        }
                    }
                    
                    $formatItem['boy_count'] = $boy_count * $formatItem['count'];
                    $formatItem['girl_count'] = $girl_count * $formatItem['count'];
                    $formatItem['count_sum'] = $formatItem['boy_count'] + $formatItem['girl_count'];
                    array_push($formatList, $formatItem);
                }
                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }
        return $response;
    }


    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的校服信息数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getUniformsCollectList($page = 1, $rows, $keywords, $arrival_code)
    {
        $sql =  'select ClotheSize.id as ClotheSizeId,Clothe.code as ClotheCode,Clothe.name as ClotheName,'
                . 'ClotheSize.code as ClotheSizeCode,ClotheSize.name as ClotheSizeName from basic_clothe_size'
                . ' as ClotheSize join basic_clothes as Clothe on ClotheSize.cloth_code = Clothe.code and '
                . 'Clothe.name like "%'. $keywords .'%" and ClotheSize.arrival_code = '.$arrival_code.' '
                . 'and Clothe.arrival_code = '.$arrival_code;
        
        $data = \DB::select(\DB::raw($sql));
        
        
        $collection = new Collection($data);

        //定义一下每页显示多少个数据
        $perPage = $rows;

        //获取当前需要显示的数据列表
        $currentPageSearchResults = $collection->slice(($page-1) * $perPage, $perPage)->all();

        //创建一个新的分页方法
        $paginatedSearchResults= new LengthAwarePaginator($currentPageSearchResults, count($collection), $perPage);
        
        
        return $paginatedSearchResults;
    }

    /***
     * 根据学生考试号获取学生详细信息
     * @param $code
     * @return mixed
     */
    private function getNewStudentByCode($code)
    {
        $student = NewStudent::where('exam_code', $code)->first();
        return $student;
    }

    /***
     * 检测是否缴费
     * @param $code
     * @return mixed
     */
    private function formatStudentSex($val)
    {
        if ($val == 1) {
            return '男';
        } elseif ($val == 2) {
            return '女';
        } else {
            return '';
        }
    }
    
    /**
     * 获取所有招生年份
     *
     * @param $code
     * @return mixed|string
     */
    private function getEnrollmentCodes()
    {
        $codes = NewArrival::all()->pluck('code')->toArray();
        return $codes;
    }
    
    /***
     * 获取当前的迎新代码
     * @return array
     */
    private function getArrivalCodes()
    {
        $code = '';
        $years = NewArrival::where('isOn',true)->first();
        if (!empty($years) || isset($years)) {
            $code = $years->code;
        }
        return $code;
    }

}
